package com.seeyon.apps.ext.ObxMsgPush.utils;

import com.seeyon.apps.weixin.util.WeixinUtil;
import com.seeyon.ctp.common.SystemEnvironment;
import com.seeyon.ctp.common.constants.ApplicationCategoryEnum;
import com.seeyon.ctp.common.i18n.ResourceUtil;
import com.seeyon.ctp.common.usermessage.Constants.UserMessage_SOURCE_TYPE;
import com.seeyon.ctp.common.usermessage.pipeline.Message;
import com.seeyon.ctp.login.online.OnlineRecorder;
import com.seeyon.ctp.login.online.OnlineUser;
import com.seeyon.ctp.organization.OrgConstants;
import com.seeyon.ctp.organization.OrgConstants.ExternalType;
import com.seeyon.ctp.organization.bo.V3xOrgMember;
import com.seeyon.ctp.util.Base64;
import com.seeyon.ctp.util.Datetimes;
import com.seeyon.ctp.util.LightWeightEncoder;
import com.seeyon.ctp.util.Strings;
import java.net.URLEncoder;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class MessageUtil {
	private static Log log = LogFactory.getLog(MessageUtil.class);

	public static String getMessageJson(Message message, String platform, String corpid) {
		String messageJson = "";
		try {
			boolean isSendMessage = true;
			if (message.getReceiverMember().getExternalType().intValue() != ExternalType.Inner.ordinal()) {
				isSendMessage = false;
			}
			if (!WeixinUtil.isOnline()) {
				OnlineUser onlineUser = OnlineRecorder.getOnlineUser(message.getReceiverMember().getLoginName());
				if (onlineUser != null) {
					Set<String> loginTypes = onlineUser.getLoginTypes();
					if ((loginTypes != null) && ((loginTypes.contains(Constants.login_useragent_from.pc.name()))
							|| (loginTypes.contains(Constants.login_useragent_from.iphone.name()))
							|| (loginTypes.contains(Constants.login_useragent_from.androidphone.name()))
							|| (loginTypes.contains(Constants.login_useragent_from.ipad.name()))
							|| (loginTypes.contains(Constants.login_useragent_from.androidpad.name())))) {
						isSendMessage = false;
					}
				}
			}
			if (isSendMessage) {
				if ((message.getCategory() == ApplicationCategoryEnum.collaboration.key())
						|| (message.getCategory() == ApplicationCategoryEnum.edoc.key())
						|| (message.getCategory() == ApplicationCategoryEnum.edocSend.key())
						|| (message.getCategory() == ApplicationCategoryEnum.edocRec.key())
						|| (message.getCategory() == ApplicationCategoryEnum.edocSign.key())
						|| (message.getCategory() == ApplicationCategoryEnum.exSend.key())
						|| (message.getCategory() == ApplicationCategoryEnum.exSign.key())
						|| (message.getCategory() == ApplicationCategoryEnum.edocRegister.key())
						|| (message.getCategory() == ApplicationCategoryEnum.edocRecDistribute.key())
						|| (message.getCategory() == ApplicationCategoryEnum.exchange.key())
						|| (message.getCategory() == ApplicationCategoryEnum.news.key())
						|| (message.getCategory() == ApplicationCategoryEnum.bulletin.key())
						|| (message.getCategory() == ApplicationCategoryEnum.bbs.key())
						|| (message.getCategory() == ApplicationCategoryEnum.show.key())
						|| (message.getCategory() == ApplicationCategoryEnum.inquiry.key())
						|| (message.getCategory() == ApplicationCategoryEnum.calendar.key())
						|| (message.getCategory() == ApplicationCategoryEnum.taskManage.key())
						|| (message.getCategory() == ApplicationCategoryEnum.meeting.key())
						|| (message.getCategory() == ApplicationCategoryEnum.attendance.key())
						|| (message.getCategory() == ApplicationCategoryEnum.office.key())
						|| (message.getCategory() == ApplicationCategoryEnum.ai.key())
						|| (message.getCategory() > 2000)) {
					if (WeixinUtil.isLink()) {
						messageJson = getMessage(message, "link", platform, corpid);
					} else {
						messageJson = getMessage(message, "text", platform, corpid);
					}
				} else if ((message.getCategory() == ApplicationCategoryEnum.doc.key())
						|| (message.getCategory() == ApplicationCategoryEnum.plan.key())
						|| (message.getCategory() == ApplicationCategoryEnum.behavioranalysis.key())
						|| (message.getCategory() == ApplicationCategoryEnum.hr.key())) {
					messageJson = getMessage(message, "text", platform, corpid);
				}
			}
		} catch (Exception e) {
			log.error("组装微信消息失败！", e);
		}
		return messageJson;
	}

	private static String getMessage(Message message, String messageType, String platform, String corpid) {
		int category = message.getCategory();
		String remoteUrl = message.getRemoteURL();
		String content = message.getContent();
		String linkType = message.getLinkType();

		String loginNane = message.getReceiverMember().getLoginName();
		byte[] bytes = loginNane.getBytes();
		byte[] baseBytes = Base64.encodeBase64(bytes, false);
		String ticket = new String(baseBytes);
		if (ticket.contains("=")) {
			ticket = ticket.replace("=", "@");
		}
		Long id = message.getReferenceId();
		if ((id != null) && (id.longValue() == -1L) && (message.getLinkParams() != null)
				&& (message.getLinkParams().length > 0)) {
			id = Long.valueOf(NumberUtils.toLong(message.getLinkParams()[0], -1L));
		}
		if (("link".equals(messageType)) && (Strings.isNotBlank(linkType))) {
			if (category == ApplicationCategoryEnum.collaboration.key()) {
				String path = "";
				if (("message.link.col.supervise".equals(linkType)) || ("message.link.col.traceRecord".equals(linkType))
						|| ("message.link.formtrigger.msg.flow".equals(linkType))
						|| ("message.link.formtrigger.msg.unflow".equals(linkType))
						|| ("message.link.formtrigger.cap4.msg.unflow".equals(linkType))) {
					content = content + " 请登录内部协同系统进行处理，谢谢！";
					remoteUrl = "";
				} else {
					path = "/seeyon/m3/apps/v5/collaboration/html/details/summary.html?affairId=" + id
							+ "&openFrom=listPending&summaryId=-1&proxyId=0";
					remoteUrl = dealWithUrl(path, ticket, platform, corpid);
				}
			} else if ((category == ApplicationCategoryEnum.edoc.key())
					|| (category == ApplicationCategoryEnum.edocSend.key())
					|| (category == ApplicationCategoryEnum.edocRec.key())
					|| (category == ApplicationCategoryEnum.edocSign.key())
					|| (category == ApplicationCategoryEnum.exSend.key())
					|| (category == ApplicationCategoryEnum.exSign.key())
					|| (category == ApplicationCategoryEnum.edocRegister.key())
					|| (category == ApplicationCategoryEnum.edocRecDistribute.key())
					|| (category == ApplicationCategoryEnum.exchange.key())) {
				String path = "";
				if (("message.link.edoc.supervise.detail".equals(linkType))
						|| ("message.link.edoc.supervise.main".equals(linkType))
						|| ("message.link.exchange.distribute".equals(linkType))
						|| ("message.link.exchange.receive".equals(linkType))
						|| ("message.link.exchange.receive.hasten".equals(linkType))
						|| ("message.link.exchange.register.govpending".equals(linkType))
						|| ("message.link.exchange.register.pending".equals(linkType))
						|| ("message.link.exchange.register.receive".equals(linkType))
						|| ("message.link.exchange.registered".equals(linkType))
						|| ("message.link.exchange.send".equals(linkType))
						|| ("message.link.exchange.sent".equals(linkType))
						|| ("message.link.edoc.traceRecord".equals(linkType))) {
					content = content + " 请登录内部协同系统进行处理，谢谢！";
					remoteUrl = "";
				} else {
					id = Long.valueOf(message.getLinkParams()[0]);
					path = "/seeyon/m3/apps/v5/edoc/html/edocSummary.html?affairId=" + id
							+ "&openFrom=listPending&summaryId=-1&proxyId=0";
					remoteUrl = dealWithUrl(path, ticket, platform, corpid);
				}
			} else if (category == ApplicationCategoryEnum.meeting.key()) {
				String path = "";
				if (("message.link.mt.room_perm".equals(linkType))
						|| ("message.link.office.meetingroom".equals(linkType))) {
					content = content + " 请登录内部协同系统进行处理，谢谢！";
					remoteUrl = "";
				} else if (("message.link.mt.summary".equals(linkType))
						|| ("message.link.mt.summary_send".equals(linkType))
						|| ("message.link.mt.send.scope".equals(linkType))) {
					path = "/seeyon/m3/apps/v5/meeting/html/meetingSummary.html?meetingSummaryId=" + id
							+ "&openFrom=message&affairId=-1&proxyId=0&proxy=false";
					remoteUrl = dealWithUrl(path, ticket, platform, corpid);
				} else {
					path = "/seeyon/m3/apps/v5/meeting/html/meetingDetail.html?meetingId=" + id
							+ "&openFrom=pending&affairId=-1&proxyId=0&proxy=false";
					remoteUrl = dealWithUrl(path, ticket, platform, corpid);
				}
			} else if (category == ApplicationCategoryEnum.news.key()) {
				String path = "/seeyon/m3/apps/v5/news/html/newsView.html?newsId=" + id + "&comeFrom=0";
				if ("message.link.news.writedetail".equals(linkType)) {
					content = content + " 请登录内部协同系统进行处理，谢谢！";
					remoteUrl = "";
				} else {
					remoteUrl = dealWithUrl(path, ticket, platform, corpid);
				}
			} else if (category == ApplicationCategoryEnum.bulletin.key()) {
				String path = "/seeyon/m3/apps/v5/bulletin/html/bulView.html?bulId=" + id + "&comeFrom=0";
				if ("message.link.bul.writedetail".equals(linkType)) {
					content = content + " 请登录内部协同系统进行处理，谢谢！";
					remoteUrl = "";
				} else {
					remoteUrl = dealWithUrl(path, ticket, platform, corpid);
				}
			} else if (category == ApplicationCategoryEnum.bbs.key()) {
				String path = "/seeyon/m3/apps/v5/bbs/html/bbsView.html?bbsId=" + id + "&from=message";
				remoteUrl = dealWithUrl(path, ticket, platform, corpid);
			} else if (category == ApplicationCategoryEnum.inquiry.key()) {
				String path = "";
				if (("message.link.inq.alreadyauditing.pass".equals(linkType))
						|| ("message.link.inq.alreadyauditing.nopass".equals(linkType))) {
					content = content + " 请登录内部协同系统进行处理，谢谢！";
					remoteUrl = "";
				} else if ("message.link.inq.auditing".equals(linkType)) {
					path = "/seeyon/m3/apps/v5/inquiry/html/inquiryView.html?inquiryId=" + id + "&comeFrom=2"
							+ "&affairState=4";
					remoteUrl = dealWithUrl(path, ticket, platform, corpid);
				} else {
					path = "/seeyon/m3/apps/v5/inquiry/html/inquiryView.html?inquiryId=" + id + "&comeFrom=0";
					remoteUrl = dealWithUrl(path, ticket, platform, corpid);
				}
			} else if (category == ApplicationCategoryEnum.show.key()) {
				String showbarId = message.getLinkParams()[0];
				StringBuilder path = new StringBuilder("/seeyon/m3/apps/v5/show/html/showbarDetail.html?id=");
				path.append(showbarId);
				if ("message.link.show.showReply".equals(linkType)) {
					content = content.replaceAll("\"", "");

					path.append("&showpostId=").append(message.getLinkParams()[1]);
					path.append("&commentId=").append(message.getLinkParams()[2]);
					path.append("&from=").append(message.getLinkParams()[3]);
				} else if ("message.link.show.newshowbar".equals(linkType)) {
					path.append("&from=").append(message.getLinkParams()[1]);
				} else if (("message.link.show.showpost.settop".equals(linkType))
						|| ("message.link.show.showPraise".equals(linkType))) {
					path.append("&showpostId=").append(message.getLinkParams()[1]);
					path.append("&from=").append(message.getLinkParams()[2]);
				}
				path.append("&openType=").append("wechat");
				remoteUrl = dealWithUrl(path.toString(), ticket, platform, corpid);
			} else if (category == ApplicationCategoryEnum.attendance.key()) {
				String path = "";
				if ("message.link.attendance.view".equals(linkType)) {
					path = "/seeyon/m3/apps/v5/attendance/html/attendanceIndex.html?from=message";
				} else {
					path = "/seeyon/m3/apps/v5/attendance/html/attendanceDetail.html?attendanceId=" + id;
				}
				remoteUrl = dealWithUrl(path, ticket, platform, corpid);
			} else if (category == ApplicationCategoryEnum.taskManage.key()) {
				StringBuilder path = new StringBuilder("/seeyon/m3/apps/v5/taskmanage/html/");
				if ("message.link.taskmanage.viewfeedback".equals(linkType)) {
					path.append("taskFeedbackList.html?openType=wechat&taskId=").append(message.getLinkParams()[0]);
				} else if ("message.link.taskmanage.status".equals(linkType)) {
					String[] linkParams = message.getLinkParams();
					path.append("task_index.html?openType=wechat&listType=" + linkParams[0] + "&status=overdue");
				} else {
					path.append("taskEditor.html?openType=wechat&taskId=").append(message.getLinkParams()[0]);
				}
				remoteUrl = dealWithUrl(path.toString(), ticket, platform, corpid);
			} else if (category == ApplicationCategoryEnum.calendar.key()) {
				StringBuilder path = new StringBuilder("/seeyon/m3/apps/v5/calendar/html/newCalEvent.html?");
				path.append("id=").append(message.getLinkParams()[0]);
				remoteUrl = dealWithUrl(path.toString(), ticket, platform, corpid);
			} else if (category == ApplicationCategoryEnum.office.key()) {
				Long affairId = Long.valueOf(-1L);
				if ((message.getLinkParams() != null) && (message.getLinkParams().length > 0)) {
					affairId = Long.valueOf(NumberUtils.toLong(message.getLinkParams()[0], -1L));
				}
				String path = "/seeyon/m3/apps/v5/office/html/";
				if ("message.link.office.autoN.audit".equals(linkType)) {
					path = path + "audit_auto.html?affairId=" + affairId;
					remoteUrl = dealWithUrl(path, ticket, platform, corpid);
				} else if ("message.link.office.stockN.audit".equals(linkType)) {
					path = path + "audit_stock.html?affairId=" + affairId;
					remoteUrl = dealWithUrl(path, ticket, platform, corpid);
				} else if ("message.link.office.assetN.audit".equals(linkType)) {
					path = path + "audit_asset.html?affairId=" + affairId;
					remoteUrl = dealWithUrl(path, ticket, platform, corpid);
				} else if ("message.link.office.bookN.audit".equals(linkType)) {
					path = path + "audit_book.html?applyId=" + id;
					remoteUrl = dealWithUrl(path, ticket, platform, corpid);
				} else {
					content = content + " 请登录内部协同系统进行处理，谢谢！";
					remoteUrl = "";
				}
			} else if (category > 2000) {
				if ((message.getLinkParams() != null) && (message.getLinkParams().length > 0)) {
					String thirdId = message.getLinkParams()[0];
					String registerCode = message.getLinkParams()[2];
					if (StringUtils.isBlank(registerCode)) {
						remoteUrl = "";
					} else if (registerCode.startsWith("http")) {
						remoteUrl = registerCode;
						if (remoteUrl.contains("?")) {
							remoteUrl = remoteUrl + "&weixinMessage=true";
						} else {
							remoteUrl = remoteUrl + "?weixinMessage=true";
						}
					} else {
						StringBuilder sb = new StringBuilder(
								"/seeyon/m3/apps/v5/portal/html/cipWeixinMessage.html?thirdpartyMessageId=");
						sb.append(thirdId);
						sb.append("&registerCode=");
						sb.append(registerCode);
						remoteUrl = dealWithUrl(sb.toString(), ticket, platform, corpid);
					}
				} else {
					remoteUrl = "";
				}
			} else if (category == ApplicationCategoryEnum.ai.key()) {
				String path = "";
				if ("message.link.col.pending".equals(linkType)) {
					path = "/seeyon/m3/apps/v5/collaboration/html/details/summary.html?affairId=" + id
							+ "&openFrom=listPending&summaryId=-1&proxyId=0";
					remoteUrl = dealWithUrl(path, ticket, platform, corpid);
				}
			}
		} else {
			remoteUrl = "";
		}
		Long receiverId = message.getReceiverMember().getId();
		Long senderId = Long.valueOf(message.getSenderMemberId());
		String sendUserName = "";
		if (senderId.longValue() == -1L) {
			if (Constants.UserMessage_SOURCE_TYPE.AI.ordinal() == message.getSourceType()) {
				sendUserName = ResourceUtil.getString("application.72.label");
			} else {
				sendUserName = ResourceUtil.getString("anonymous.label");
			}
		} else {
			sendUserName = message.getSenderMember().getName();
		}
		StringBuilder messagePo = new StringBuilder();
		messagePo.append("{");
		messagePo.append("D:'" + Datetimes.formatDatetime(message.getCreateDate()) + "'");
		messagePo.append(",S:'" + Strings.escapeJavascript(sendUserName) + "'");
		messagePo.append(",R:'" + receiverId + "'");
		messagePo.append(",C:'" + Strings.escapeJavascript(content) + "'");
		messagePo.append(",U:'" + remoteUrl + "'");
		messagePo.append(",M:'" + category + "'");
		messagePo.append(",L:'" + linkType + "'");
		messagePo.append(",I:'" + WeixinUtil.getOaUrl() + "'");
		messagePo.append("}");
		return messagePo.toString();
	}
	private static String dealWithUrl(String url, String ticket, String platform, String corpid) {
		String messageUrl = "";
		url = url + "&weixinMessage=true";
		if ("weixin".equals(platform)) {
			if (!url.contains(".do")) {
				log.info(new StringBuilder()
								.append("http://183.65.43.11:94")
								.append("/seeyon/H5/collaboration/messageIndex.html?html=").append(url).toString());
				messageUrl = "http://183.65.43.11:94" + "/content/viewh5Message?url="
						+ URLEncoder.encode(LightWeightEncoder.encodeString(new StringBuilder()
								.append("http://183.65.43.11:94")
								.append("/seeyon/H5/collaboration/messageIndex.html?html=").append(url).toString()));
			} else {
				log.info(new StringBuilder().append("http://183.65.43.11:94")
						.append("/seeyon/thirdpartyController.do?method=access&enc=").append("C=")
						.append(ticket).append("&P=").append(url).toString());
				messageUrl = "http://183.65.43.11:94" + "/content/index?url="
						+ URLEncoder.encode(
								LightWeightEncoder.encodeString(new StringBuilder().append("http://183.65.43.11:94")
										.append("/seeyon/thirdpartyController.do?method=access&enc=").append("C=")
										.append(ticket).append("&P=").append(url).toString()));
				
			}
		} else if ("dingding".equals(platform)) {
			try {
				String redirect_uri = URLEncoder.encode(
						WeixinUtil.getOaUrl() + SystemEnvironment.getContextPath()
								+ "/wechat/dingding.do?method=viewh5Message&html=" + URLEncoder.encode(url, "UTF-8"),
						"UTF-8");
				messageUrl = "https://oapi.dingtalk.com/connect/oauth2/authorize?appid=" + corpid + "&redirect_uri="
						+ redirect_uri + "&response_type=code&scope=snsapi_base&state=" + corpid;
			} catch (Exception e) {
				log.error("", e);
			}
		}
		return messageUrl;
	}
}
